import React from 'react';
import { FooterToolbar, PageContainer } from '@ant-design/pro-layout';
import type { ChargerItem } from '@/services/API.d';
import { columnsChargerItem } from '@/services/Column.d';
import type { ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import {
  addCharger,
  queryChargerList,
  removeCharger,
  upCharger,
  updateCharger,
  downCharger,
} from '@/services/charger';
import ProForm, { ModalForm, ProFormSelect, ProFormText } from '@ant-design/pro-form';

type StateType = {
  isEdit: boolean;
  visible: boolean;
  currentRow: ChargerItem;
  selectedRowsState: ChargerItem[];
};

class Charger extends React.Component<any, StateType> {
  private actionRef = React.createRef<any>();
  private formRef = React.createRef<any>();
  private temp: ChargerItem = {
    id: 0,
    cardType: 1,
    stationType: 1,
    charge: 0,
    state: 1,
  };
  public state = {
    isEdit: false,
    visible: false,
    currentRow: this.temp,
    selectedRowsState: [],
  };

  setCurrentRow = (currentRow: ChargerItem) => {
    this.setState({
      currentRow,
    });
  };

  setSelectedRows = (selectedRowsState: ChargerItem[]) => {
    this.setState({
      selectedRowsState,
    });
  };

  /**
   * 添加节点
   * @param fields
   */
  handleAdd = async (fields: ChargerItem) => {
    const hide = message.loading('正在添加');

    try {
      const res = await addCharger({ ...fields });
      hide();
      if (res.code === 200) {
        message.success(res.msg);
        return true;
      }
      message.error(res.msg);
      return false;
    } catch (error) {
      hide();
      message.error('添加失败，请重试！');
      return false;
    }
  };

  /**
   *  删除节点
   * @param selectedRows
   */
  handleRemove = async (selectedRows: ChargerItem[]) => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;

    try {
      await removeCharger(selectedRows.map((row) => row.id));
      hide();
      message.success('删除成功');
      return true;
    } catch (error) {
      hide();
      message.error('删除失败，请重试');
      return false;
    }
  };

  /**
   *  状态更新节点
   * @param selectedRows
   * @param state
   */
  handleUpdateState = async (selectedRows: ChargerItem[], state: number) => {
    const hide = message.loading('正在操作');
    if (!selectedRows) return true;
    try {
      if (state === 1) {
        await upCharger(selectedRows.map((row) => row.id));
      } else if (state === 2) {
        await downCharger(selectedRows.map((row) => row.id));
      }
      hide();
      message.success('操作成功');
      return true;
    } catch (error) {
      hide();
      message.error('操作失败，请重试');
      return false;
    }
  };

  /**
   * 更新节点
   * @param fields
   */
  handleUpdate = async (fields: ChargerItem) => {
    const hide = message.loading('正在编辑');

    try {
      const res = await updateCharger({ ...fields });
      hide();
      if (res.code === 200) {
        message.success(res.msg);
        return true;
      }
      message.error(res.msg);
      return true;
    } catch (error) {
      hide();
      message.error('编辑失败请重试！');
      return false;
    }
  };

  render() {
    const { isEdit, visible, selectedRowsState, currentRow } = this.state;

    const { actionRef, formRef } = this;

    const columns: ProColumns<ChargerItem>[] = columnsChargerItem;
    columns[columns.length - 1].render = (_, record) => (
      <>
        <a
          onClick={() => {
            this.setCurrentRow(record);
            formRef.current?.setFieldsValue(record);
            this.setState({
              visible: true,
              isEdit: true,
            });
          }}
        >
          编辑
        </a>
      </>
    );
    return (
      <PageContainer>
        <ProTable<ChargerItem>
          headerTitle="收费标准列表"
          actionRef={actionRef}
          rowKey={(record) => record.id}
          search={{
            labelWidth: 120,
          }}
          pagination={{
            showQuickJumper: true,
          }}
          toolBarRender={() => [
            <Button
              type="primary"
              key="primary"
              onClick={() => {
                this.setCurrentRow(this.temp);
                formRef.current?.setFieldsValue(this.temp);
                this.setState({
                  visible: true,
                  isEdit: false,
                });
              }}
            >
              <PlusOutlined /> 新建
            </Button>,
          ]}
          dateFormatter="string"
          request={ async (params) => {
            // 表单搜索项会从 params 传入，传递给后端接口。
            let res: any = {};
            await queryChargerList(params).then(v => {
              res = v;
              res.total = v.msg
            })
            return res;
          }}
          columns={columns}
          rowSelection={{
            onChange: (_, selectedRows) => this.setSelectedRows(selectedRows),
          }}
        />
        {selectedRowsState?.length > 0 && (
          <FooterToolbar
            extra={
              <div>
                已选择 <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a> 项
              </div>
            }
          >
            <Button
              onClick={async () => {
                await this.handleRemove(selectedRowsState);
                this.setSelectedRows([]);
                actionRef.current?.reloadAndRest?.();
              }}
            >
              批量删除
            </Button>
            <Button
              type="primary"
              onClick={async () => {
                await this.handleUpdateState(selectedRowsState, 1);
                this.setSelectedRows([]);
                actionRef.current?.reloadAndRest?.();
              }}
            >
              批量上架
            </Button>
            <Button
              onClick={async () => {
                await this.handleUpdateState(selectedRowsState, 2);
                this.setSelectedRows([]);
                actionRef.current?.reloadAndRest?.();
              }}
            >
              批量下架
            </Button>
          </FooterToolbar>
        )}
        <ModalForm
          title={isEdit ? '编辑收费类息' : '新建收费类型'}
          formRef={formRef}
          visible={visible}
          onVisibleChange={(e) => {
            if (!e) {
              this.setState({
                visible: false,
              });
            }
          }}
          onFinish={async (values) => {
            let success;
            if (!isEdit) {
              success = await this.handleAdd(values as ChargerItem);
            } else {
              success = await this.handleUpdate(values as ChargerItem);
            }
            if (success) {
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
            return true;
          }}
        >
          <ProForm.Group>
            <ProFormText
              width="md"
              name="charge"
              label="停车价格"
              placeholder="请输入停车价格"
              initialValue={currentRow.charge}
              rules={[
                {
                  required: true,
                  message: '停车价格为必填项',
                },
              ]}
            />
            <ProFormSelect
              options={[
                {
                  value: 1,
                  label: '上架',
                },
                {
                  value: 2,
                  label: '下架',
                },
              ]}
              initialValue={currentRow.state}
              width="md"
              name="state"
              label="状态"
              placeholder="请选择状态"
              rules={[
                {
                  required: true,
                  message: '状态为必选项',
                },
              ]}
            />
            <ProFormText name="id" hidden initialValue={currentRow.id} />
          </ProForm.Group>
          {!isEdit && (
            <ProForm.Group>
              <ProFormSelect
                width="md"
                name="cardType"
                label="停车卡类型"
                placeholder="请输入停车卡类型"
                initialValue={currentRow.cardType}
                options={[
                  {
                    value: 1,
                    label: '普通卡',
                  },
                  {
                    value: 2,
                    label: 'VIP卡',
                  },
                ]}
                rules={[
                  {
                    required: true,
                    message: '车位号为必填项',
                  },
                ]}
              />
              <ProFormSelect
                width="md"
                name="stationType"
                label="车位类型"
                placeholder="请选择车位类型"
                initialValue={currentRow.stationType}
                options={[
                  {
                    value: 1,
                    label: '小型',
                  },
                  {
                    value: 2,
                    label: '中型',
                  },
                  {
                    value: 3,
                    label: '大型',
                  },
                ]}
                rules={[
                  {
                    required: true,
                    message: '车位类型为必填项',
                  },
                ]}
              />
            </ProForm.Group>
          )}
        </ModalForm>
      </PageContainer>
    );
  }
}

export default Charger;
